package x.trident.core.config.center.inject;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.util.TypeUtils;
import com.alibaba.nacos.api.exception.NacosException;
import org.apache.commons.lang3.reflect.FieldUtils;
import org.springframework.stereotype.Component;

import java.lang.reflect.Field;

/**
 * 类的功能
 *
 * @author 林选伟
 * @date 2021/9/4 1:11 下午
 */
@Component
public class InjectFuncImpl implements InjectFunc {
    /**
     * 为field注入配置值
     *
     * @param bean  bean
     * @param field 被TridentConfig注解的字段
     * @param value 配置值
     * @throws NacosException 可能抛错异常
     */
    @Override
    public void inject(Object bean, Field field, Object value) throws NacosException {


        Class<?> type = field.getType();
        Object finalValue;

        // 进行类型转换
        if (type.isAssignableFrom(String.class)) {
            finalValue = value;
        } else if (type.isAssignableFrom(Integer.class)) {
            finalValue = TypeUtils.castToInt(value);
        } else if (type.isAssignableFrom(Double.class)) {
            finalValue = TypeUtils.castToDouble(value);
        } else if (type.isAssignableFrom(Long.class)) {
            finalValue = TypeUtils.castToLong(value);
        } else {
            finalValue = JSON.parseObject((String) value, field.getGenericType());
        }

        try {
            FieldUtils.writeField(field, bean, finalValue, true);
        } catch (Exception e) {
            throw new NacosException(500, String.format("%s类中%s属性中的TridentConfig注解配置value:%s注入失败", bean.getClass(), field.getName(), value));
        }

    }
}